package priv.books.service;

import cn.hutool.core.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import priv.books.pojo.*;
import priv.books.mapper.OrderMapper;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private BooksService booksService;

    @Autowired
    private SaleService saleService;

    /**
     * 查询所有信息
     * @param order
     * @return
     */
    public List<Order> getAllInfo(Order order) {
        return orderMapper.getAllInfo(order);
    }

    /**
     * 插入订单
     * @param orderDetailFrom
     * @return
     */
    public boolean insertInfo(OrderDetailFrom orderDetailFrom) {
        // 创建订单信息
        Order order = new Order();
        order.setCreateDate(DateUtil.now());
        order.setOrderNum(DateUtil.format(new Date(), "yyyyMMddHHmmssSSS"));
        // 计算订单详情集合中的小计价格
        order.setOrderPrice(orderDetailFrom.getOrderDetails().stream().map(OrderDetail::getTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add));
        // 插入订单
        boolean saveOrder = this.save(order);
        if(!saveOrder) {
            throw new RuntimeException("新增订单失败！");
        }
        // 插入订单详情
        saveOrderDetail(order, orderDetailFrom.getOrderDetails());
        // 调用修改商品销量方法
        updateBooksInfo(orderDetailFrom.getOrderDetails());
        // 插入销售记录 (第一个参数是订单信息, 第二个参数是订单中卖出的书籍数量)
        saveSale(order, orderDetailFrom.getOrderDetails().stream().mapToInt(OrderDetail::getPayNum).sum());
        return true;
    }

    /**
     * 插入销量记录
     * @param order
     * @param payNum
     */
    private void saveSale(Order order, Integer payNum) {
        // 插入销售记录
        Sale sale = new Sale();
        sale.setCreateDate(order.getCreateDate());
        sale.setPrice(order.getOrderPrice());
        sale.setType("1");
        sale.setSaleNum(payNum);
        boolean saveSale = saleService.save(sale);
        if(!saveSale) {
            throw new RuntimeException("新增销量记录时出现错误！");
        }
    }

    /**
     * 更新商品销量
     * @param orderDetails
     */
    private void updateBooksInfo(List<OrderDetail> orderDetails) {
        List<Integer> booksIds = new ArrayList<>(16);
        orderDetails.forEach(item -> {
            booksIds.add(item.getBooksId());
        });
        // 修改商品销量, (首先查询所有相关书籍当前的数据信息)
        List<Books> booksList = booksService.getByIds(booksIds);
        for (Books books : booksList) {
            for (OrderDetail orderDetail : orderDetails) {
                if(books.getId().equals(orderDetail.getBooksId())) {
                    // 判断库存是否足够
                    if(books.getBookStock() < orderDetail.getPayNum()) {
                        throw new RuntimeException(books.getBookName() + "的库存不足！");
                    }
                    // 修改销量
                    books.setSalesVolume(books.getSalesVolume() + orderDetail.getPayNum());
                    books.setBookStock(books.getBookStock() - orderDetail.getPayNum());
                }
            }
        }
        booksService.updateBatchById(booksList);
    }

    /**
     * 保存订单详情
     * @param orderDetails
     */
    private void saveOrderDetail(Order order, List<OrderDetail> orderDetails) {
        orderDetails.forEach(item -> {
            item.setOrderId(order.getId());
        });
        boolean saveOrderDetail = orderDetailService.saveBatch(orderDetails);
        if(!saveOrderDetail) {
            throw new RuntimeException("插入订单详情时出现错误！");
        }
    }
}
